package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    //阅读
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
//        1. 校验参数 文章id必须传
        if(dto==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(),dto.getEquipmentId());
//        3. 判断阅读行为是否存在
        Query query = Query.query(Criteria
                .where("entryId").is(apBehaviorEntry.getId())
                .and("articleId").is(dto.getArticleId())
        );
        ApReadBehavior apReadBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
//       4. 存在  将阅读行为的count字段加1 并修改
        if(apReadBehavior!=null){
        apReadBehavior.setCount((short) (apReadBehavior.getCount()+1));
        mongoTemplate.save(apReadBehavior);
        }else {
//        5. 不存在  创建阅读行为 并初始化count字段值为 1
            ApReadBehavior apr = new ApReadBehavior();
            apr.setEntryId(apBehaviorEntry.getId());
            apr.setArticleId(dto.getArticleId());
            apr.setCount((short) 1);
            mongoTemplate.save(apr);
        }
        return ResponseResult.okResult();
    }
}
